package logic.ships.autoWeaponShip;

import java.util.ArrayList;
import java.util.List;

import logic.nodes.lod.blocks.AbstractBlock;
import logic.nodes.lod.blocks.Block;
import logic.nodes.lod.blocks.LeafBlock;
import logic.ships.moveableShip.MovableShip;

public abstract class BlockFinder {
	
	protected MovableShip ship;
	protected float range;
	protected List<LeafBlock> leafBlocks;
	
	public BlockFinder(MovableShip ship) {
		this.ship = ship;
		
		leafBlocks = new ArrayList<LeafBlock>();
	}
	
	public abstract float getRange();
	
	public List<LeafBlock> getNearestLeafBlocks() {
		if(!needsUpdate() && !leafBlocks.isEmpty()) return leafBlocks;
		
		updateBlocks();
		
		return leafBlocks;
	}
	
	protected void updateBlocks() {
		leafBlocks.clear();
		range = getRange() + ship.getSize();
		checkSubBlocks(ship.getIngameState().getRootBlock());
	}
	
	protected void checkSubBlocks(Block block) {
		checkBlock(block.getBlockA());
		checkBlock(block.getBlockB());
	}
	
	protected void checkBlock(AbstractBlock block) {
		if(block.intersectsWith(ship)) {
			if(block instanceof Block) checkSubBlocks((Block)block);
			else {
				LeafBlock leafBlock = (LeafBlock)block;
				float dist = ship.getLocalTranslation().distance(leafBlock.getCenter()) - leafBlock.getSize();
				if(dist <= range) leafBlocks.add(leafBlock);
			}
		}
	}
	
	protected boolean needsUpdate() { return range != getRange(); }
}